package com.xtourms.client.util;

import java.util.Date;

import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.Format;

public class MysqlDateFormat implements Format {

	/**
	 * Default style name added when the date box has a format error.
	 */
	private static final String DATE_BOX_FORMAT_ERROR = "dateBoxFormatError";
	
	public MysqlDateFormat(){
	}
	
	@Override
	public String format(DateBox dateBox, Date date) {
		if (date == null) {
	        return "";
	    } else {
	    	java.sql.Date sd = new java.sql.Date(date.getTime());
	    	return sd.toString();
	    }
	}

	@Override
	public Date parse(DateBox dateBox, String text, boolean reportError) {
		Date date = null;
		try {
			if (text.length() > 0) {
				date = java.sql.Date.valueOf(text);
			}
		} catch (IllegalArgumentException exception) {
			if (reportError) {
				dateBox.addStyleName(DATE_BOX_FORMAT_ERROR);
			}
			return null;
		}
		return date;
	}

	@Override
	public void reset(DateBox dateBox, boolean abandon) {
		dateBox.removeStyleName(DATE_BOX_FORMAT_ERROR);
	}

}
